<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2020-05-07
 */

namespace app\api\model\v1;

use think\Db;
use think\Cache;
use think\Config;

/**
 * 微信小程序商城商品模型
 */
load_trait('controller/Jump');

class ScoreGoods extends Base
{
    use \traits\controller\Jump;

    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
    }
    // 检测提交的商品是否可兑换
    public function detectionGoods($post = [])
    {
        if (!empty($post['product_id'])) {
            if (!empty($post['spec_value_id'])) {
                $where = [
                    'aid' => $post['product_id'],
                    'score_stock' => ['>', 0],
                    'spec_value_id' => $post['spec_value_id']
                ];
                $field = 'score_stock';
                $specStock = Db::name('product_spec_value')->where($where)->getField($field);
                if (empty($specStock)) $this->error('商品已兑完！');
                if (intval($specStock) < intval($post['product_num'])) $this->error('商品最大库存：' . $specStock);
            } else {
                $where = [
                    'aid' => $post['product_id'],
                    'status' => 1,
                    'is_del' => 0
                ];
                $stockCount = Db::name('memgift')->where($where)->getField('stock');

                if (empty($stockCount)) $this->error('商品已兑完！');
                if (intval($stockCount) < intval($post['product_num'])) $this->error('商品最大库存：' . $stockCount);
            }
        }
    }

    // 查询商品信息列表(购物车商品 或 立即购买商品)
    public function getGoodsBuyList($cacheData = [], $usersID = 0)
    {
        // 立即购买商品
        $where = [
            'a.aid' => !empty($cacheData['product_id']) ? intval($cacheData['product_id']) : 0,
        ];
        // 多规格条件
        if (!empty($cacheData['spec_value_id'])) $where['b.spec_value_id'] = $cacheData['spec_value_id'];
        // 查询字段
        $field = 'd.stock,d.score, d.freight_fee_set, d.freight_fee_tpl,a.aid, a.typeid, a.title, a.litpic, a.users_price, a.stock_count, a.prom_type, a.attrlist_id, b.value_id, b.aid as product_id, b.spec_value_id, b.score_need, b.score_stock,b.score_price, c.template_id, c.status as template_status, c.template_ids, c.template_data, c.special_set, c.special_ids';

        $goodsList = Db::name('memgift')
            ->alias('d')
            ->field($field)
            ->join('archives a', 'a.aid = d.aid', 'LEFT')
            ->join('__PRODUCT_SPEC_VALUE__ b', 'a.aid = b.aid', 'LEFT')
            ->join('__SHOP_FREIGHT_TEMPLATE__ c', 'a.freight_fee_tpl = c.template_id', 'LEFT')
            ->where($where)
            ->limit(1)
            ->select();
        $goodsList[0]['product_num'] = $cacheData['product_num'];

        return $goodsList;
    }

    // 处理商品规格、会员折扣
    public function getGoodsHandleResult($goodsList = [], $usersDiscount = 1, $source = 'goodsBuy')
    {
        foreach ($goodsList as $key => $value) {
            // 未开启多规格则执行(未定义 或 未开启)
            if (!isset($this->usersConfig['shop_open_spec']) || empty($this->usersConfig['shop_open_spec'])) {
                $value['spec_value_id'] = $value['score_need'] = $value['score_price'] = $value['score_stock'] = 0;
            }

            // 多规格商品则使用规格库存覆盖商品原库存，后续做真实计算
            if (!empty($value['spec_value_id'])) $value['stock'] = intval($value['score_stock']);

            // 库存为0则清除这条数据并跳过本次循环以下操作
            if (empty($value['stock'])) {
                unset($goodsList[$key]);
                continue;
            }

            // 多规格商品则使用规格价格覆盖商品原价格，后续做真实计算
//            if (!empty($value['spec_value_id'])) $value['users_price'] = floatval($value['spec_price']);
            if (!empty($value['spec_value_id'])) $value['score'] = intval($value['score_need']);

//            // 商品原价--处理金额
//            $value['old_price'] = unifyPriceHandle($value['users_price']);
//
//            // 计算会员折扣价
//            if (!empty($usersDiscount)) $value['users_price'] = floatval($value['users_price']) * floatval($usersDiscount);

            // 商品实价--处理金额
//            $value['users_price'] = unifyPriceHandle($value['users_price']);
//            $value['users_price_arr'] = explode('.', $value['users_price']);

            // 购买数量超过最大库存量则默认购买最大库存量
            if (intval($value['product_num']) > intval($value['stock'])) $value['product_num'] = intval($value['stock']);

            // 图片处理
            $value['litpic'] = $this->get_default_pic($value['litpic'], true);

            // 规格值组装处理
            $value['product_spec'] = [];
            if (!empty($value['spec_value_id'])) {
                $specValueID = explode('_', $value['spec_value_id']);
                if (!empty($specValueID)) {
                    $where = [
                        'aid' => $value['product_id'],
                        'spec_value_id' => ['IN', $specValueID]
                    ];
                    $ProductSpecData = Db::name("product_spec_data")->where($where)->field('spec_value')->select();
                    foreach ($ProductSpecData as $value_1) {
                        $value['product_spec'][] = !empty($value_1['spec_value']) ? $value_1['spec_value'] : '';
                    }
                }
            }
            $value['product_spec'] = !empty($value['product_spec']) ? implode('；', $value['product_spec']) : '';

            // 覆盖原商品数据
            $goodsList[$key] = $value;
        }

        return $goodsList;
    }

    // 商品数据整合处理
    public function getGoodsPriceHandle($goodsList = [], $globalParam = [])
    {
        foreach ($goodsList as $key => $value) {
            // 合计金额、合计数量计算
            if ($value['score'] >= 0 && !empty($value['product_num'])) {
                // 计算合计数量
                $globalParam['orderTotalNum'] += intval($value['product_num']);
                // 计算单品小计
                $subtotal = floatval($value['users_price']) * floatval($value['product_num']);
                $value['subtotal'] = unifyPriceHandle($subtotal);
                $globalParam['payUseScoresNum'] += $value['score'] * intval($value['product_num']);
                // 计算合计金额
                $globalParam['orderTotalAmount'] += floatval($subtotal);
                $globalParam['orderTotalAmount'] = unifyPriceHandle($globalParam['orderTotalAmount']);
            }

            // 覆盖原数据
            $goodsList[$key] = $value;
        }

        return [
            'goodsList' => $goodsList,
            'globalParam' => $globalParam
        ];
    }

    // 商品库存扣除
    public function goodsStockDeduct($upSpecValue = [])
    {
        if (!empty($upSpecValue)) {
            // 循环组装数据
            $arcData = $specData = [];
            foreach ($upSpecValue as $key => $value) {
                if (!empty($value['value_id'])) {
                    // 普通订单
                    $specData[] = [
                        'value_id' => $value['value_id'],
                        'score_stock' => Db::raw('score_stock-' . ($value['quantity'])),
                        'score_sales_num' => Db::raw('score_sales_num+' . ($value['quantity'])),
                    ];
                    $arcData = [
                        'stock' => Db::raw('stock-' . ($value['quantity'])),
                        'num'   => Db::raw('num+' . ($value['quantity'])),
                        'update_time'   => getTime()
                    ];
                } else {
                    // 普通订单
                    $arcData = [
                        'stock' => Db::raw('stock-' . ($value['quantity'])),
                        'num'   => Db::raw('num+' . ($value['quantity'])),
                        'update_time'   => getTime()
                    ];
                }
                // 更新积分商品库存销量=
                Db::name('memgift')->where([ 'aid' => $value['aid']])->update($arcData);
            }

            // 更新规格库存销量
            if (!empty($specData)) {
                $productSpecValueModel = new \app\user\model\ProductSpecValue();
                $productSpecValueModel->saveAll($specData);
            }

            // 更新商品库存销量
//            if (!empty($arcData)) {
//                $archivesModel = new \app\user\model\Archives();
//                $archivesModel->saveAll($arcData);
//            }
        }
    }
}